var app = getApp();
import {
  api,
  util,
  dialog,
  forms,
  storage
} from '../../../js/util'
import {
  router
} from '../../../js/router';
import {
  fastorder,
  order,
  cart
} from "../../../js/modules/order.js"
import {
  detail,
  mall,
  list,
  scant,
  specModel
} from "../../../js/modules/mall.js";
import {
  activities
} from "../../../js/modules/market.js";
import authorize from '../../../js/modules/authorize.js'
import {
  GoodsNumCache
} from '../../../js/modules/propertycache.js'
const componentBehavior = require('../../../js/common/ComponentBehavior')
import { alert, deepClone, isEmpty, sleep } from '../../../js/newUtil';

Component({
  behaviors: [componentBehavior],
  lifetimes: {
    attached() {
      //this.outofstock = this.selectComponent("#outofstock");
      
    },
    detached() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  /**
   * 组件的属性列表
   */
  properties: {
    product:{
      type:Object,
      value:{}
    },
    goodSpecific: {
      type: Array,
      value: []
    },
    goodlist: {
      type: Array,
      value: []
    },
    specifictions:{
      type:Array,
      value:[]
    },
    goodsIndex:{
      type:Number,
      value:0
    },
    quantityDigits: {
      type: Number,
      value: 0
    },
    priceDigits: {
      type: Number,
      value: 2
    },
    isScanty: {
      type: Boolean,
      value: false
    },
    //规格展示样式
    spectStyle: {
      type: Number,
      value: 0
    },
    //不同规格单位换算关系不相同
    enableSKUTranslated:{
      type:Boolean,
      value:false
    },
    specObj:{
      type:Object,
      value:{}
    },
    Currency:String,//货币符号
    NoLoginShowPrice:Boolean,
    isLogin:Boolean,
    listState:Boolean,
    IsGoodsTrading:Boolean,
    GoodsUnitDisplayMode:{
      value:0,
      type:Number
    },
    isShowBuyLowerLimit:Boolean,
    FrontShowStockDetail:Boolean,
    DisplayBatchJoinCartArea: { // 规格组合列表模式，是否展示批量加购交互区域
      type: Boolean,
      value: false
    },
    DisplaySpecHorizontalSwitchArea: { // 规格组合列表模式，是否展示规格横向切换区域
      type: Boolean,
      value: false
    },
    BatchJoinCartUnits: { // 批量加购时的单位列表
      type: Array,
      value: [],
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    index:0,
    type:'',
    multipleChangeData: { // 组合列表模式时的数据
      currentId: '', // 当前商品的 productId_ProductGoodsId
      value: 0, // 统一修改时的值
      AuxiliaryUnits: [], // 商品单位列表
      ZIndex: 0, // 当前选中的单位的index
      specIndex: 0, // 商品第一个规格选中的index
      goodsIds: '', // 商品ids
      Unit: '', // 基础单位
      cacheList: [], // 缓存当前顶部规格批量修改的单位和数量
    },
    tips: {
      max: [], // 到达最大数量的商品的信息
      message: [], // 需要提示的信息
    },
    hideInputAtWindow: false, // 隐藏商品添加区域
    mainColor: api.titleColor || "#e56b14", // 主题色
  },

  observers: {
    goodSpecific () {
      // 组合列表时，单位为第一个规格的单位
      let BatchJoinCartUnits = this.data.BatchJoinCartUnits || []
      let goodSpecific = this.data.goodSpecific || []
      let specifictions = this.data.specifictions || []
      let product = this.data.product || {}
      let multipleChangeData = this.data.multipleChangeData
      let currentId = `${product.ProductId}_${product.ProductGoodsId}` // 当前id的标识符
      if (currentId == multipleChangeData.currentId) { // 当id相等时才判断，不等时则是用户切换了更多系列，需要重新再修改批量单位
        if (multipleChangeData.AuxiliaryUnits.length != 0) { // 已存在规格则不再继续刷新
          return
        }
      }
      multipleChangeData.AuxiliaryUnits = []
      multipleChangeData.currentId = currentId
      if (BatchJoinCartUnits.length > 0) {
        multipleChangeData.AuxiliaryUnits = BatchJoinCartUnits
        multipleChangeData.Unit = ''
        multipleChangeData.ZIndex = 0
      } else if (goodSpecific.length > 0) {
        let item = deepClone(goodSpecific[0])
        multipleChangeData.AuxiliaryUnits = item.AuxiliaryUnits
        multipleChangeData.Unit = item.Unit
        multipleChangeData.ZIndex = item.ZIndex
      }
      let defaultUnit = product.DefaultUnit || ''
      for (let i = 0; i < multipleChangeData.AuxiliaryUnits.length; i++) {
        if (defaultUnit && multipleChangeData.AuxiliaryUnits[i].Name == defaultUnit) {
          multipleChangeData.ZIndex = i
          multipleChangeData.Unit = multipleChangeData.AuxiliaryUnits[i].Name
        }
        multipleChangeData.AuxiliaryUnits[i].Qty = 0
      }
      if (multipleChangeData.ZIndex > multipleChangeData.AuxiliaryUnits.length) {
        multipleChangeData.ZIndex = 0
      }
      if (multipleChangeData.cacheList.length == 0) {
        if (specifictions.length > 0) {
          let arr = specifictions[0].SpecValue
          for (let i = 0; i < arr.length; i++) {
            multipleChangeData.cacheList.push({
              CartCount: 0,
              ZIndex: multipleChangeData.ZIndex || 0
            })
          }
        }
      }
      this.setData({
        multipleChangeData
      })
    },
    specifictions (specifictions = []) {
      this.specChange(specifictions)
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 点规格事件
     */
    onSpectEvent: function (e) {
      let { product, goodSpecific } = this.data;
      specModel.onSpectEvent(e.currentTarget.dataset, this.data, (res) => {
        if (res.goodsIndex != -1) {
          product.BuyUpperLimit = res.goodSpecific[res.goodsIndex].SBuyUpperLimit;
          product.BuyLowerLimit = res.goodSpecific[res.goodsIndex].SBuyLowerLimit;
          product.SBuyUpperLimit = res.goodSpecific[res.goodsIndex].SBuyUpperLimit;
          product.SBuyLowerLimit = res.goodSpecific[res.goodsIndex].SBuyLowerLimit;
        }
        this.setData({
          specifictions: res.specifictions
        });
        if(res.goodsIndex == -1){
          product.BuyUpperLimit = product.SBuyUpperLimit;
          product.BuyLowerLimit = product.SBuyLowerLimit;
        }
        this.triggerEvent("onGoodsChangeEvent", { product: product, goods: goodSpecific[res.goodsIndex], goodsIndex: res.goodsIndex,currentIndex:res.currentIndex, specifictions: res.specifictions });
      });
    },
    imgIndex(e){
      let { product, goodSpecific } = this.data;
      specModel.onSpectEvent(e.currentTarget.dataset, this.data, (res) => {
        this.setData({
          specifictions: res.specifictions,
          index:e.currentTarget.dataset.idxs
        });
        this.triggerEvent("onGoodsChangeEvent", { product: product, goods: goodSpecific[res.goodsIndex], goodsIndex: res.goodsIndex,currentIndex:res.currentIndex, specifictions: res.specifictions });
      });
    },
    /**
     * 改变数量
     */
    onNumChage: function (e) {
      var num = e.detail.value;
      if (num < 0) {
        num = 0;
      }
      let idx = e.detail.idx;
      let index = e.detail.unitIndex;
      let limit = e.detail.limit || {}
      let { goodSpecific, product} = this.data;
      let g = this.changeGoodsNumItem(goodSpecific, num, idx, index)
      let message = this.alertMessage(g, limit.sMax, product)
      if (message) {
        alert(message)
      }
      this.triggerEvent("onGoodsChangeEvent", { product:product, goods: g, goodsIndex: idx });
    },
    /**
   * 展开----收起
   */
    bindUnfold(e){
      var index=e.currentTarget.dataset.index;
      console.log(index,'---===');
      this.data.goodSpecific[index].show = !this.data.goodSpecific[index].show
      this.setData({
        goodSpecific:this.data.goodSpecific
      })
    },
    /**
     * 改变单位
     */
    onChangeGoodsUnitEvent: function (e) {
      let { goodSpecific, product } = this.data;
      let { gidx, idx } = e.currentTarget.dataset;
      let g = this.changeGoodsUnitItem(goodSpecific, gidx, idx)
      this.triggerEvent("onGoodsChangeEvent", { product: product, goods: g, goodsIndex: gidx });
    },
    unitList(AuxiliaryUnits,UnitPrices,CartCount){
      for(var i=0;i<AuxiliaryUnits.length;i++){
        var t = detail.parseRule(UnitPrices, AuxiliaryUnits[i].Translated, AuxiliaryUnits[i].Qty || 0, false);
        if(t.has){
          AuxiliaryUnits[i].price = t.price;
          if(t.integral){
            AuxiliaryUnits[i].integral = t.integral;
          }
        }
      }
    },
    validateSelectStatus() {
      let { specifictions, goodSpecific,goodsIndex, spectStyle } = this.data;
      let index = -1;
      if (spectStyle==1){
        specModel.setGoodsIndex(specifictions, goodSpecific, -1, (res) => {
          // index = res.currentIndex == -1?goodsIndex:res.currentIndex;
          index = res.currentIndex == -1? specifictions.length == 0?goodsIndex:res.currentIndex:res.currentIndex;
        });
        return index;
      }
      else return true;
    },
    /**
     * 批量加入购物车
     */
    onAddCarEvent(addCompleted) {
      var that = this;
      let {spectStyle} = that.data;
      if (this.data.init_timeout) {
        clearTimeout(this.data.init_timeout);
      }
      this.data.init_timeout = setTimeout(() => {
        let { product, goodSpecific } = that.data;
        var index = -1, carts = [], totalQuantity = 0;
        //零售模式只组装选中的规格
        if(spectStyle==1){
          index = this.validateSelectStatus();
          if(index==-1){
            util.tips("请先选择购买商品规格！");
            return;
          }
        }
        for (var i = 0; i < goodSpecific.length; i++) {
          var goods = goodSpecific[i];
          // if (spectStyle == 1 && i != index) {
          //   continue;
          // }
          if (goods.AuxiliaryUnits&&goods.AuxiliaryUnits.length>0) {
            for(var j = 0; j < goods.AuxiliaryUnits.length; j++){
              var unit = goods.AuxiliaryUnits[j];
              var auxQty = unit.Qty || 0;
              var auxRate = unit.Translated || 1;
              var auxUnit = unit.Name || '';
              var quantity = auxQty * auxRate;
              if(auxQty> 0){
                carts.push(`<Goods>
                <FkFlag>2</FkFlag>
                <FkId>${goods.FKId||app.dns.proprietorId}</FkId>
                <ProductId>${goods.ProductId}</ProductId>
                <GoodsId>${goods.GoodsId}</GoodsId>
                <SpecValue><![CDATA[${goods.SpecValue}]]></SpecValue>
                <DiscountId>${goods.DiscountId || 0}</DiscountId>
                <DiscountType>${goods.DiscountType || 0}</DiscountType>
                <Quantity>${quantity}</Quantity>
                <AuxQty>${auxQty}</AuxQty>
                <AuxRate>${auxRate}</AuxRate>
                <AuxUnit>${auxUnit}</AuxUnit>
                </Goods>`);
              }
              totalQuantity += quantity;
            }
          }else if(goods.CartCount > 0){
            var auxQty = goods.CartCount || 0;
            var auxRate = goods.Translated || goods.Radix;
            var auxUnit = goods.DefaultUnit || goods.AuxUnit;
            var quantity = auxQty * auxRate;
            carts.push(`<Goods>
            <FkFlag>2</FkFlag>
            <FkId>${goods.FKId||app.dns.proprietorId}</FkId>
            <ProductId>${goods.ProductId}</ProductId>
            <GoodsId>${goods.GoodsId}</GoodsId>
            <SpecValue><![CDATA[${goods.SpecValue}]]></SpecValue>
            <DiscountId>${goods.DiscountId || 0}</DiscountId>
            <DiscountType>${goods.DiscountType || 0}</DiscountType>
            <Quantity>${quantity}</Quantity>
            <AuxQty>${auxQty}</AuxQty>
            <AuxRate>${auxRate}</AuxRate>
            <AuxUnit>${auxUnit}</AuxUnit>
            </Goods>`);
            totalQuantity += quantity;
          }
        }
        if (totalQuantity == 0) {
          util.tips("请确定需要购买的货品数量！");
          return;
        }
        product.CartCount = totalQuantity;
        setTimeout(() => {
          cart.batchAddCart(carts.join(""),(status, content)=>{
            if (status) {
              for (var i = 0; i < goodSpecific.length; i++) {
                var goods = goodSpecific[i];
                if (spectStyle == 1 && i != index) {
                  continue;
                }
                if (goods.AuxiliaryUnits&&goods.AuxiliaryUnits.length>0) {
                  for(var j = 0; j < goods.AuxiliaryUnits.length; j++){
                    var unit = goods.AuxiliaryUnits[j];
                    if (unit.Qty > 0) {
                      GoodsNumCache.add(goods.ProductId, goods.GoodsId, unit.Qty, unit.Translated);
                    } else {
                      GoodsNumCache.del(goods.GoodsId);
                    }
                  }
                }else if(goods.CartCount > 0){
                  GoodsNumCache.add(goods.ProductId, goods.GoodsId, goods.CartCount, goods.Translated || goods.Radix);
                }else{
                  GoodsNumCache.del(goods.GoodsId);
                }
              }
              // 显示数改为直接使用后台返回的数据
              // 最小销售单位非基础单位时页面显示需要改为根据当前最小销售单位的换算显示,采用后台数据
              if (!isEmpty(content.Products) && Array.isArray(content.Products)) {
                for (let i = 0; i < content.Products.length; i++) {
                  if (product.ProductId == content.Products[i].ProductId) {
                    product.CartCount = content.Products[i].Quantity
                    break
                  }
                }
              }
              if (typeof (addCompleted) == "function") {
                addCompleted(product);
              }
            }else{
              util.tips(content||"加入购物车失败");
            }
          });
        }, 500);
      }, 100);

    },
    /**
     * 多规格商品弹出层的立即购买 */
    onBuyEvent(addCompleted) {
      let { quantityDigits } = this.data
      var that = this;
      if (that.data.init_timeout) {
        clearTimeout(that.data.init_timeout);
      }
      this.data.init_timeout = setTimeout(() => {
        let { product, goodSpecific,spectStyle,GoodsUnitDisplayMode}=that.data;
        var goods_arr = [];
        if(GoodsUnitDisplayMode == 1){
          if(spectStyle == 1){
            var index = that.validateSelectStatus();
            if(index==-1){
              util.tips("请选择属性");
              return;
            }
          }
          for (var i = 0; i < goodSpecific.length; i++) {
            var g = goodSpecific[i];
            for(var j=0;j < g.AuxiliaryUnits.length; j++){
              var q = g.AuxiliaryUnits[j];
              if(q.Qty > 0){
                goods_arr.push(g);
              }
            }
          }
        }else{
          if(spectStyle==1){
            var index = that.validateSelectStatus();
            if(index==-1){
              util.tips("请选择属性");
              return;
            }
            var selectSpec = goodSpecific[index];
            if(selectSpec.CartCount > 0){
              var g = selectSpec;
              g.ProductGoodsId = g.GoodsId;
              g.num = g.CartCount;
              goods_arr.push(g);
            }
          }else{
            for (var i = 0; i < goodSpecific.length; i++) {
              if (goodSpecific[i].CartCount > 0) {
                var g = goodSpecific[i];
                g.ProductGoodsId = g.GoodsId;
                g.num = g.CartCount;
                goods_arr.push(g);
              }
            }
          }
        }
        if (goods_arr.length == 0) {
          util.tips("请确定货品购买数量");
          return;
        }
        setTimeout(function(){
          var productinfo = '';
          if(GoodsUnitDisplayMode == 1){
            if(spectStyle == 1){
              productinfo = order.buyNows([goodSpecific[index]],product, quantityDigits);
            }else{
              productinfo = order.buyNows(goodSpecific,product, quantityDigits);
            }
            
          }else{
            productinfo = order.buyNows(goodSpecific,product, quantityDigits);
          }
          console.log(goods_arr,productinfo,index);
          // return;
          var params = {
            path: "orderConfirm",
            params: {
              productinfo: productinfo
            }
          }
          if (typeof (addCompleted) == "function") {
            addCompleted();
          }
          router.navigate(params);
        },500)
      }, 100);
    },
    /**
     * 显示缺货登记
     */
    onShowScanty: function (e) {
      var that = this;
      var idx = e.currentTarget.dataset.idx;
      var goods = that.data.goodSpecific[idx];
      var product = that.data.product;
      var goodlist = that.data.goodlist[idx];
      goods.BrandId = product.BrandId;
      goods.ProductName = product.ProductName;
      goods.ProductGoodsId = goods.GoodsId;
      goods.DefaultPic = goodlist.DefaultPic;
      goods.MultipleBuy = product.MultipleBuy;
      if(that.data.EnableSKUTranslated!=1){
        let units = goods.AuxiliaryUnits||[];
        goods.productUnitText = detail.loadUnitContext(units, goods.Unit);
      }
      console.log(goods,'=========onShowScanty',goods);
      this.triggerEvent("onShowScantyEvent", goods);
    },
    showStockDistribution(e) {
      var gidx = e.currentTarget.dataset.index;
      var goods = this.data.goodSpecific[gidx];
      this.triggerEvent("showStockDistribution", goods);
    },
    preventTouchMove() {

    },
    /*查看大图*/
    bindImg(e){
      var imgsList = e.currentTarget.dataset.src;
      this.triggerEvent("lookImg", {imgsList:imgsList,index:this.data.index})
    },
    /**选中规格*/
    onClickItem(e){
      let { product, goodSpecific, goodsIndex, specifictions } = this.data;
      var gidx = e.currentTarget.dataset.index;
      if (gidx == goodsIndex) {
        goodsIndex = -1;
      }else{
        goodsIndex = gidx;
      }
      if (goodsIndex != -1) {
        var goods = goodSpecific[goodsIndex];
        product.BuyUpperLimit = goods.SBuyUpperLimit;
        product.BuyLowerLimit = goods.SBuyLowerLimit;
      }else{
        product.BuyUpperLimit = product.SBuyUpperLimit;
        product.BuyLowerLimit = product.SBuyLowerLimit;
      }
      this.triggerEvent("onGoodsChangeEvent", { product: product, goods: goodSpecific[goodsIndex], goodsIndex: goodsIndex,currentIndex: goodsIndex, specifictions: specifictions  });
    },
    /**
     * 修改当前商品项的单位
     * @param {Array} goodSpecific 规格列表
     * @param {Array} gidx 当前规格的index
     * @param {Array} idx 当前修改的单位的index
     */
    changeGoodsUnitItem: function (goodSpecific = [], gidx = 0, idx = 0) {
      let g = goodSpecific[gidx] || {}
      let AuxiliaryUnits = goodSpecific[gidx].AuxiliaryUnits || []
      if (idx == -1) {
        return g
      }
      let unit = AuxiliaryUnits[idx]
      g.Translated = unit.Translated
      g.DefaultUnit = unit.Name
      g.ZIndex = idx
      g.CartCount = unit.Qty
      g.BuyLowerLimit = unit.BuyLowerLimit
      g.BuyUpperLimit = unit.BuyUpperLimit
      g.Stock = unit.Stock
      let price_obj = detail.parseRule(g.UnitPrices, g.Translated, g.CartCount, g.Translated==1)
      if (price_obj.has) {
        g.SalesPrice = price_obj.price
        g.SalesIntegral = price_obj.integral
        g.originalPrice = price_obj.originalPrice
        g.Price = price_obj.MarketPrice
      }
      return g
    },
    /**
     * 修改当前商品规格的商品数量
     * @param {*} goodSpecific 规格列表
     * @param {*} num 修改的数量
     * @param {*} gidx 当前规格的index
     * @param {*} index 当前修改的单位的index
     * @param {Boolean} isMultiple 是否为批量修改
     */
    changeGoodsNumItem: function (goodSpecific = [], num, gidx, index, isMultiple = false) {
      let {
        quantityDigits,
        GoodsUnitDisplayMode,
        product
      } = this.data
      let MultipleBuy = product.MultipleBuy || 1
      let g = goodSpecific[gidx]
      if (!g) {
        console.log('商品数据错误', g)
        return {}
      }
      let ZeroStockBuy = g.ZeroStockBuy
      let PanicBuy = product.PanicBuy || []
      PanicBuy = PanicBuy[0] || {}
      let type = PanicBuy.type || -1 // 商品类型，3是特价
      let marketGoods = PanicBuy.marketGoods || PanicBuy.PanicGoods || [] // 特价商品列表
      let marketIds = marketGoods.map(i => parseInt(i.GoodsId)) // 特价商品Id
      let GoodsId = parseInt(g.GoodsId || g.ProductGoodsId) // 当前商品的GoodsId
      let isPanicBuyGoods = marketIds.includes(GoodsId) // 是否是特价商品（多规格商品可能只有部分是特价，需要再次判断）
      let ExceedLimitOriginalPriceBuy = PanicBuy.ExceedLimitOriginalPriceBuy || 0 // 特价商品超限加购
      // 批量修改时，要提前判断数量与最大最小值等的关系，防止input组件内部再去操作导致闪烁的问题
      if (isMultiple) {
        let translated = g.AuxiliaryUnits[g.ZIndex || 0].Translated
        let count = num * translated // 转化为基础单位时的数量
        let changed = false
        let message = ''
        let min = g.BuyLowerLimit || 0 // 最小可购买值
        let max = 0 // 最大可购买值
        if (g.Stock != 0 && g.BuyUpperLimit != 0) {
          if (type == 3 && ExceedLimitOriginalPriceBuy == 1 && isPanicBuyGoods) {
            // 开启了特价商品超限加购，则最大值就是商品库存
            max = g.Stock
          } else {
            max = Math.min(g.Stock, g.BuyUpperLimit) || 0
          }
        } else if (g.Stock == 0) { // 库存为0，则最大值为0
          max = 0
        } else if (g.BuyUpperLimit == 0) {
          if (g.SBuyUpperLimit == 0) { // 没有限制最大购买，则为库存数
            max = g.Stock || 0
          } else {
            // 可购买的商品数量为0
            if (type == 3 && ExceedLimitOriginalPriceBuy == 1 && isPanicBuyGoods) {
              // 开启了特价商品超限加购，则最大值就是商品库存
              max = g.Stock || 0
            } else {
              max = 0
            }
          }
        }
        // 开启0库存下单，则重设最大值
        if (ZeroStockBuy == 1) {
          max = 999999
        }
        // 倍数购买时，判断最大最小值是否满足倍数关系
        if (g.Translated == 1 && MultipleBuy > 0) {
          // 最小值不满足倍数购买关系，改为大于最小值接近的倍数数量
          if (min % MultipleBuy !== 0) {
            min = Math.ceil(util.precisionDiv(min, MultipleBuy))
            min = util.precisionX(min, MultipleBuy)
          }
          // 最大值不满足倍数购买关系，改为小于最大值接近的倍数数量
          if (max % MultipleBuy !== 0) {
            max = Math.floor(util.precisionDiv(max, MultipleBuy))
            max = util.precisionX(max, MultipleBuy)
          }
        }
        if (count > 0) {
          let reset = false
          // 小于最小购买值时，为最小值
          if (min > 0 && count < min) {
            count = Math.ceil(min / translated)
            changed = true
            reset = true
          }
          let diff = count
          if (reset) {
            // 当用最小值的数据重置过count时，后续计算需要换算倍数
            diff = count * translated
          }
          // 当大于最大购买数量时，变为最大购买数量
          if (max > 0 && diff > max) {
            count = Math.floor(max / translated)
            message = g.SpecValue || ''
            changed = true
            reset = true
          }
        }
        // 最大购买数量为0，则变更为0
        if (max == 0) {
          count = 0
          message = g.SpecValue || ''
          changed = true
        }
        if (changed) {
          num = count
        }
        if ((g.SStock<=0 || (!g.isPanic&&g.SStock < product.SBuyLowerLimit)) && ZeroStockBuy == 0) {
          // 库存不足时，不增加提示信息
        } else {
          // 当超过数量限制，则添加商品信息，用于弹窗提示
          let tips = this.data.tips
          let max = tips.max || []
          if (!max.includes(message) && message) {
            tips.message.push(message)
            tips.max.push(message)
            this.setData({
              tips
            })
          }
        }
      }
      if(GoodsUnitDisplayMode == 1 && g.AuxiliaryUnits && g.AuxiliaryUnits.length > 1){
        g.AuxiliaryUnits[index].Qty = num;
        g.CartCount = 0;
        let totalUnitQuantity = 0 // 全部的规格数量
        for(var i=0;i<g.AuxiliaryUnits.length;i++){
          var item = g.AuxiliaryUnits[i];
          var otherAuxiliaryUnits = g.AuxiliaryUnits.filter(unit=>{return unit.Translated != item.Translated});
          var otherUnitQuantity = 0;
          if (otherAuxiliaryUnits&&otherAuxiliaryUnits.length>0) {
              otherAuxiliaryUnits.map((child, idx) => {
                  if (child.Qty!=undefined&&child.Qty>0) {
                      otherUnitQuantity += (child.Qty || 0) * (child.Translated || 1);
                  }
              });
          }
          item.BuyLowerLimit = g.SBuyLowerLimit > 0 && g.SBuyLowerLimit > otherUnitQuantity ? util.keepDecimal("ceil", g.SBuyLowerLimit - otherUnitQuantity, quantityDigits) : 0;
          item.BuyUpperLimit = g.SBuyUpperLimit > 0 && g.SBuyUpperLimit > otherUnitQuantity ? util.keepDecimal("ceil", g.SBuyUpperLimit - otherUnitQuantity, quantityDigits) : 0;
          item.Stock = g.SStock > 0 && g.SStock > otherUnitQuantity ? util.keepDecimal("ceil", g.SStock - otherUnitQuantity, quantityDigits) : 0;
          g.CartCount += item.Qty * item.Translated;
          totalUnitQuantity += (item.Qty || 0) * (item.Translated || 1)
        }
        g.totalUnitQuantity = totalUnitQuantity
        let price_obj = detail.parseRule(g.UnitPrices, (g.AuxiliaryUnits[index].Translated || g.Radix),num == 0?1:num,true);
        if (price_obj.has) {
          //如果价格没有变化时，则不给数据源重新绑定值
          if (g.AuxiliaryUnits[index].price != price_obj.price || (g.AuxiliaryUnits[index].price || 0) != (price_obj.integral || 0)) {
            g.AuxiliaryUnits[index].integral = price_obj.integral;
            g.AuxiliaryUnits[index].price = price_obj.price;
          }
        }
      }else{
        g.CartCount = num;
        g.AuxiliaryUnits[g.ZIndex || 0].Qty = num;
        let totalUnitQuantity = 0 // 全部的规格数量
        for(var i=0;i<g.AuxiliaryUnits.length;i++){
          var item = g.AuxiliaryUnits[i];
          var otherAuxiliaryUnits = g.AuxiliaryUnits.filter(unit=>{return unit.Translated != item.Translated});
          var otherUnitQuantity = 0;
          if (otherAuxiliaryUnits&&otherAuxiliaryUnits.length>0) {
              otherAuxiliaryUnits.map((child, idx) => {
                  if (child.Qty!=undefined&&child.Qty>0) {
                      otherUnitQuantity += (child.Qty || 0) * (child.Translated || 1);
                  }
              });
          }
          item.BuyLowerLimit = g.SBuyLowerLimit > 0 && g.SBuyLowerLimit > otherUnitQuantity ? util.keepDecimal("ceil", g.SBuyLowerLimit - otherUnitQuantity, quantityDigits) : 0;
          item.BuyUpperLimit = g.SBuyUpperLimit > 0 && g.SBuyUpperLimit > otherUnitQuantity ? util.keepDecimal("ceil", g.SBuyUpperLimit - otherUnitQuantity, quantityDigits) : 0;
          item.Stock = g.SStock > 0 && g.SStock > otherUnitQuantity ? util.keepDecimal("ceil", g.SStock - otherUnitQuantity, quantityDigits) : 0;
          if(item.Translated == (g.Translated||g.Radix)){
            g.BuyLowerLimit = item.BuyLowerLimit;
            g.BuyUpperLimit = item.BuyUpperLimit;
            g.Stock = item.Stock;
          }
          totalUnitQuantity += (item.Qty || 0) * (item.Translated || 1)
        }
        g.totalUnitQuantity = totalUnitQuantity
        let price_obj = detail.parseRule(g.UnitPrices, (g.Translated || g.Radix), num, (g.Translated || g.Radix)==1);
        if (price_obj.has) {
          //如果价格没有变化时，则不给数据源重新绑定值
          if (g.SalesPrice != price_obj.price || (g.SalesIntegral || 0) != (price_obj.integral || 0)) {
            g.SalesIntegral = price_obj.integral;
            g.SalesPrice = price_obj.price;
          }
        }
      }
      // 批量修改时，如果基础单位设置了倍数购买，计算当前数量最近的倍数值
      if (isMultiple) {
        if (g.Translated == 1 && MultipleBuy > 0 && MultipleBuy != 1) {
          let _rate = Math.ceil(util.precisionDiv(g.CartCount, MultipleBuy))
          g.CartCount = util.precisionX(_rate, MultipleBuy)
          if (GoodsUnitDisplayMode == 1 && g.AuxiliaryUnits && g.AuxiliaryUnits.length > 1) {
            // 单位列表模式，并且有多单位
            // 规格组合列表模式，单位全部为切换模式，无需处理此方法
          } else {
            // 修改每个单位中的值，满足倍数购买规则，防止提交校验失败
            g.AuxiliaryUnits[g.ZIndex || 0].Qty = g.CartCount
          }
        }
      }
      return g
    },
    /**
     * 组合列表模式，修改顶部的规格
     * @param {*} e 
     */
    changeGroupListSpec (e) {
      let {
        multipleChangeData
      } = this.data
      let index = e.currentTarget.dataset.idxs
      multipleChangeData.specIndex = index
      multipleChangeData.CartCount = multipleChangeData.cacheList[multipleChangeData.specIndex].CartCount || 0
      multipleChangeData.ZIndex = multipleChangeData.cacheList[multipleChangeData.specIndex].ZIndex || 0
      this.setData({
        multipleChangeData,
        index
      })
    },
     /**
     * 同时修改多个规格的选中单位
     * @param {*} e 
     */
    multipleChangeUnit (e) {
      let data = this.changeUnit(e)
      let index = e.currentTarget.dataset.idx // 当前修改单位的index
      let multipleChangeData = this.data.multipleChangeData || {}
      let product = data.product || {}
      let goodSpecific = data.goodSpecific || []
      let lastItemIndex = data.lastItemIndex
      let specifictions = data.specifictions
      this.triggerEvent('onGoodsChangeMultipleEvent', {
        product,
        goodSpecific,
        lastItemIndex: lastItemIndex,
        specifictions: specifictions
      })
      try {
        multipleChangeData.CartCount = multipleChangeData.AuxiliaryUnits[index].Qty || 0
        // 当前输入内容写入缓存，切换顶部规格时，需要读取
        multipleChangeData.cacheList[multipleChangeData.specIndex].CartCount = multipleChangeData.AuxiliaryUnits[index].Qty || 0
        this.setData({
          multipleChangeData,
        })
      } catch (e) {}
    },
    /**
     * 批量购买修改数量
     * @param {*} e 
     */
    multipleChangeValue (e) {
      let that = this
      var num = e.detail.value
      if (num < 0) {
        num = 0
      }
      let multipleChangeData = this.data.multipleChangeData
      let index = multipleChangeData.ZIndex
      // 修改数量时，需要将当前显示的全部规格的单位改为批量修改的单位
      let data = this.changeUnit({
        currentTarget: {
          dataset: {
            idx: index,
            edit: false
          }
        }
      })
      let product = data.product || {}
      let specifictions = data.specifictions || []
      let goodSpecific = data.goodSpecific || []
      goodSpecific = deepClone(goodSpecific)
      let ids = [] // 当前显示规格的ids
      let lastItemIndex = data.lastItemIndex // 当前显示的规格中最后一个规格的index
      try {
        ids = specifictions[0].SpecValue[multipleChangeData.specIndex].GoodsIds
        ids = ids.split(',')
      } catch(e) {
        ids = []
      }
      let outOfPanicLimit = false // 特价商品是否超过限购数
      for (let i = 0; i < goodSpecific.length; i++) {
        let item = goodSpecific[i] || {}
        let id = item.GoodsId || ''
        let specIndex = index
        id = id.toString()
        // 只有当前展示的规格才修改其数量
        if (!ids.includes(id) && specifictions.length > 1){
          continue
        }
        // 批量修改，只修改和批量相同单位的规格
        // 即：批量选中单位为 个 时，只修改下面 个 被选中的规格, 其他规格不修改
        try {
          let specName = multipleChangeData.AuxiliaryUnits[index].Name
          specIndex = goodSpecific[i].AuxiliaryUnits.findIndex(i => i.Name == specName)
        } catch (error) {
          console.log('批量修改单位失败：', error)
        }
        if (specIndex != -1) {
          if (goodSpecific[i].ZIndex != specIndex) {
            continue
          }
          item = this.changeGoodsNumItem(goodSpecific, num, i, specIndex, true)
        }
        lastItemIndex = i
        goodSpecific[i] = item
        let input = that.selectComponent(`#input_${id}`)
        if (input) {
          let limit = input.data.limit || {}
          let message = this.alertMessage(item, limit.sMax, product)
          if (message) {
            outOfPanicLimit = true
          }
        }
      }
      if (outOfPanicLimit) {
        alert('特价商品，超出部分按原价结算')
      }
      let tips = this.data.tips
      let message = tips.message || []
      // 当存在超过数量限制的商品时，弹窗提示
      if (message.length > 0) {
        message = message.join(', ')
        alert({
          title: '超出了数量限制',
          content: `以下商品规格数量超过了可购买的最大数量，已修改为最大值：\n${message}`
        })
      }
      tips.message = []
      this.setData({
        tips
      })
      // 当只有一个规格组时，会显示全部的规格列表
      if (specifictions.length <= 1) {
        lastItemIndex = goodSpecific.length - 1
      }
      if (lastItemIndex == -1) {
        lastItemIndex = 0
      }
      this.triggerEvent('onGoodsChangeMultipleEvent', {
        product,
        goodSpecific,
        lastItemIndex: lastItemIndex,
        specifictions: specifictions
      })
      try {
        multipleChangeData.AuxiliaryUnits[index].Qty = num
        multipleChangeData.CartCount = num
        // 当前输入内容写入缓存，切换顶部规格时，需要读取
        multipleChangeData.cacheList[multipleChangeData.specIndex].CartCount = multipleChangeData.CartCount
        this.setData({
          multipleChangeData
        })
      } catch (e) {}
    },
    /**
     * 批量修改单位，并返回修改后的商品规格等数据
     * @param {*} e 
     */
    changeUnit (e) {
      let product = this.data.product || {}
      let specifictions = this.data.specifictions || []
      let goodSpecific = this.data.goodSpecific || []
      goodSpecific = deepClone(goodSpecific)
      let multipleChangeData = this.data.multipleChangeData
      let index = e.currentTarget.dataset.idx // 当前修改单位的index
      let ids = [] // 当前显示规格的ids
      let lastItemIndex = -1 // 当前显示的规格中最后一个规格的index
      multipleChangeData.ZIndex = index
      try {
        ids = specifictions[0].SpecValue[multipleChangeData.specIndex].GoodsIds
        ids = ids.split(',')
      } catch(e) {
        ids = []
      }
      // 将所有的规格的单位改为批量购买设置的单位
      for (let i = 0; i < goodSpecific.length; i++) {
        let item = goodSpecific[i] || {}
        let id = item.GoodsId || ''
        let specIndex = -1
        id = id.toString()
        if (ids.includes(id)){
          lastItemIndex = i
        } else {
          // 当前未展示的规格不修改其单位
          if (specifictions.length > 1) {
            continue
          }
        }
        // 批量修改，只修改和批量相同单位的规格
        try {
          let specName = multipleChangeData.AuxiliaryUnits[index].Name
          specIndex = goodSpecific[i].AuxiliaryUnits.findIndex(i => i.Name == specName)
        } catch (error) {
          console.log('批量修改单位失败：', error)
        }
        if (specIndex != -1) {
          item = this.changeGoodsUnitItem(goodSpecific, i, specIndex)
        }
        goodSpecific[i] = item
      }
      if (e.currentTarget.dataset.edit !== false) { // 非修改数量调用变更单位时，要将内容重新写入data
        // 单位写入缓存，切换顶部规格时，需要读取
        multipleChangeData.cacheList[multipleChangeData.specIndex].ZIndex = index
        this.setData({
          multipleChangeData,
        })
      }
      // 当只有一个规格组时，会显示全部的规格列表
      if (specifictions.length <= 1) {
        lastItemIndex = goodSpecific.length - 1
      }
      if (lastItemIndex == -1) {
        lastItemIndex = 0
      }
      return {
        product,
        goodSpecific,
        lastItemIndex: lastItemIndex,
        specifictions: specifictions
      }
    },
    /**
     * 提示用户超出特价的数量
     * @param {*} g 商品规格信息
     * @param {*} sMax 原限制购买的数量
     * @param {*} product 商品信息
     */
    alertMessage(g, sMax = 0, product = {}) {
      let item = product
      let totalUnitQuantity = g.totalUnitQuantity
      let PanicBuy = item.PanicBuy || []
      PanicBuy = PanicBuy[0] || {}
      let type = PanicBuy.type || -1
      let ExceedLimitOriginalPriceBuy = PanicBuy.ExceedLimitOriginalPriceBuy || 0
      let marketGoods = PanicBuy.marketGoods || PanicBuy.PanicGoods || []
      let marketIds = marketGoods.map(i => parseInt(i.GoodsId)) // 特价商品Id
      let GoodsId = parseInt(g.GoodsId || g.ProductGoodsId) // 当前商品的GoodsId
      let isPanicBuyGoods = marketIds.includes(GoodsId) // 是否是特价商品（多规格商品可能只有部分是特价，需要再次判断）
      if (type != 3 || ExceedLimitOriginalPriceBuy != 1 || !isPanicBuyGoods) {
        return ''
      }
      // 限定了最大值才提示
      let originalProductData = g.originalProductData || {} // 商品规格原始数据
      let originalStock = originalProductData.Stock || 0 // 商品规格的最大库存
      if (item.SBuyUpperLimit > 0 || g.Stock <= originalStock) {
        let good = {}
        for (let i = 0; i < marketGoods.length; i++) {
          if (marketGoods[i].ProductId == item.ProductId && marketGoods[i].GoodsId == GoodsId) {
            good = marketGoods[i]
          }
        }
        let max = 999999
        let unit = ''
        if (!isEmpty(good)) {
          if (good.MaxQuantity == 0 && good.Stock > 0) {
            max = good.Stock
          } else {
            max = good.MaxQuantity
          }
          unit = item.Unit || ''
        } else {
          max = sMax
          unit = item.Unit || ''
        }
        if (totalUnitQuantity > max) {
          let message = `限优惠${max || ''}${unit || ''},超出将以原售价加购`
          return message
        }
      }
      return ''
    },
    /**
     * 当规格信息变化时，判断橱窗模式product-input区域是否显示
     */
    specChange (specifictions = []) {
      let hideInputAtWindow = false // 隐藏商品添加区域
      for (let i = 0; i < specifictions.length; i++) {
        let SpecValue = specifictions[i].SpecValue || []
        let index = SpecValue.findIndex((item) => {
          return item.Checked
        })
        if (index == -1) {
          hideInputAtWindow = true
          break
        }
      }
      this.setData({
        hideInputAtWindow
      })
    },
  }
})
